package br.com.cast.dao;

import java.util.Iterator;

import javax.persistence.Query;

import org.springframework.stereotype.Component;

import br.com.cast.modelo.NotaFiscal;
@Component
public class NotaFiscalDAO extends BaseDAO<NotaFiscal> {

	public NotaFiscalDAO() {

	}

	public Iterator<NotaFiscal> consultaPaginada(long inicio, long total) {

		Query query = getEntityManager().createQuery("from NotaFiscal");

		query.setFirstResult((int) inicio);
		query.setMaxResults((int) total);

		return query.getResultList().iterator();

	}

	public boolean notaFicalCadastrada(NotaFiscal notaFiscal) {

		StringBuilder hql = new StringBuilder();
		hql.append("select count(*) as qtd").append("from NotaFiscal")
				.append("where numero = :numero");

		if (notaFiscal.getId() != null) {
			hql.append("and id <> :id");
		}

		Query query = getEntityManager().createQuery(hql.toString());
		
		query.setParameter("numero", notaFiscal.getNumero());
		
		if (notaFiscal.getId() != null) {
		//alteração
			query.setParameter("id", notaFiscal);
		}
		
		return (long)query.getSingleResult() > 0;
	}

}
